package com.comleader.operator.service;

import static com.comleader.operator.pojo.entity.table.SysConfigTableDef.SYS_CONFIG;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.comleader.operator.common.page.PageQuery;
import com.comleader.operator.mapper.SysConfigMapper;
import com.comleader.operator.pojo.entity.SysConfigEntity;
import com.comleader.operator.pojo.param.ConfigParam;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;

/**
 * 配置表 服务层实现。
 *
 * @author 连新景
 * @since 1.0
 */
@CacheConfig(cacheNames = "sys_config")
@Service
public class SysConfigService extends ServiceImpl<SysConfigMapper, SysConfigEntity> {
    @Resource
    private CacheManager cacheManager;

    @PostConstruct
    public void init() {
        list().forEach(data -> {
            cacheManager.getCache("sys_config").put(data.getParamKey(), data);
        });
    }

    public Page<SysConfigEntity> selectPage(ConfigParam param) {
        QueryWrapper queryWrapper = QueryWrapper.create().where(SYS_CONFIG.NAME.like(param.getName())).and(SYS_CONFIG.PARAM_KEY.like(param.getParamKey()));
        return page(PageQuery.build(param), queryWrapper);
    }

    @Cacheable(key = "#paramKey")
    public SysConfigEntity selectByKey(String paramKey) {
        return getOne(QueryWrapper.create().where(SYS_CONFIG.PARAM_KEY.eq(paramKey)));
    }

    @CachePut(key = "#sysConfig.paramKey")
    public SysConfigEntity saveConfig(SysConfigEntity sysConfig) {
        save(sysConfig);
        return sysConfig;
    }

    @CachePut(key = "#sysConfig.paramKey")
    public SysConfigEntity updateConfig(SysConfigEntity sysConfig) {
        updateById(sysConfig);
        return sysConfig;
    }

    @CacheEvict(key = "#paramKey")
    public boolean delete(String paramKey) {
        return remove(QueryWrapper.create().where(SYS_CONFIG.PARAM_KEY.eq(paramKey)));
    }

    /**
     * @Description 校验是否唯一
     * @Auhtor 连新景
     * @Date 2024/07/16 16:20
     * @param sysConfigEntity
     * @return boolean
     */
    public boolean checkConfigUnique(SysConfigEntity sysConfigEntity) {
        SysConfigEntity tempConfig = getOne(QueryWrapper.create().where(SYS_CONFIG.PARAM_KEY.eq(sysConfigEntity.getParamKey())));
        return tempConfig == null || tempConfig.getId().equals(sysConfigEntity.getId());
    }
}